package com.ddm.controller.web;

import com.baomidou.mybatisplus.extension.api.R;
import com.ddm.entity.webEntity.Plan;
import com.ddm.result.Result;
import com.ddm.service.webService.PlanService;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

;

/**
 * 套餐控制器
 */
@Slf4j
@RestController
@RequestMapping("/user/plan")
public class PlanController {

    @Resource
    private PlanService planService;

    /**
     * 统计每个套餐的订阅次数
     */
    @GetMapping("/countSubscribes")
    public Result<Map<String, Integer>> countPlanSubscribes() {
        Map<String, Integer> data = planService.countPlanSubscribes();
        return Result.success(data);
    }

    // 修改套餐接口
    @PutMapping("/update")
    public Result updatePlan(@RequestBody Plan plan) {
        // 校验 plan.getId() 非空（必须传入要修改的套餐ID）
        log.info(plan.toString());
        if (plan.getId() == null) {
            return Result.error("套餐ID不能为空");
        }
        try {
            boolean success = planService.updatePlan(plan);
            if (success) {
                return Result.success("修改成功");
            } else {
                // 可能是没有字段变化，而非真失败
                return Result.success("未修改任何内容");
            }
        } catch (Exception e) {
            // 捕获异常（如价格为负、数据库连接失败等）
            return Result.error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 添加新套餐
     */
    @PostMapping("/add")
    @Operation(summary = "添加新套餐", description = "创建新的套餐信息，ID由系统自动生成")
    public Result<Plan> addPlan(
            @Parameter(description = "套餐信息，不需要填写ID")
            @Valid @RequestBody Plan plan) {
        // 添加时确保ID为空，由系统生成
        if (plan.getId() != null) {
            return Result.error("添加套餐时不能指定ID，ID由系统自动生成");
        }
        try {
            // 验证套餐基本信息
            if (plan.getPlanName() == null || plan.getPlanName().trim().isEmpty()) {
                return Result.error("套餐名称不能为空");
            }
            if (plan.getDiscountPrice() == null || plan.getDiscountPrice().compareTo(BigDecimal.ZERO) < 0) {
                return Result.error("套餐价格不能为负数");
            }

            Plan savedPlan = planService.addPlan(plan);
            log.info("添加套餐成功，套餐ID: {}", savedPlan.getId());
            return Result.success(savedPlan);
        } catch (Exception e) {
            log.error("添加套餐失败", e);
            return Result.error("添加套餐失败：" + e.getMessage());
        }
    }

    //禁用/启用套餐

    // 获取所有套餐信息的接口
    @GetMapping("/listAll")
    public Result<List<Plan>> getAllPlans() {
        try {
            List<Plan> plans = planService.getAllPlans();
            return Result.success(plans);
        } catch (Exception e) {
            log.error("获取套餐列表失败", e);
            return Result.error("获取套餐列表失败：" + e.getMessage());
        }
    }

    // 新增：获取对应套餐信息的接口
    @GetMapping("/info")
    public Result<Plan> getPlanById( @RequestParam(required = true) Long planId) {
        try {
            Plan plan = planService.getPlanById(planId);
            if (plan == null) {
                return Result.error("套餐不存在"); // 明确提示“套餐不存在”
            }
            return Result.success(plan);
        } catch (Exception e) {
            log.error("查询套餐失败，planId: {}", planId, e);
            return Result.error("查询套餐失败：" + e.getMessage());
        }
    }

    /**
     * 启用套餐接口
     */
    @PutMapping("/enable")
    public Result<String> enablePlan(
            @ApiParam("套餐ID") Long planId
    ) {
        Result result=planService.enablePlan(planId);
        return result;
    }

    /**
     * 禁用套餐接口
     */
    @PutMapping("/disable")
    public Result<String> disablePlan(
            @ApiParam("套餐ID") Long planId
    ) {
        Result result=planService.disablePlan(planId);
        return result;
    }

    /**
     * 禁用套餐接口
     */
    @DeleteMapping("/delete")
    public Result<String> deletePlan(
            @ApiParam("套餐ID") Long planId
    ) {
        Result result=planService.deletePlan(planId);
        return result;
    }
}